package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.CategoryEnum;
import com.qianniu.napi.admin.entity.penum.FantimeType;
import com.qianniu.napi.admin.entity.penum.Mediatype;
import com.qianniu.napi.admin.entity.penum.Rtype;
import com.qianniu.napi.admin.service.IBannerService;
import com.qianniu.napi.admin.service.IConfigService;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.OrderActor;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.admin.service.akka.StoreActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.EncryptUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import com.qianniu.napi.common.util.VideoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2018-06-15
 */
@Controller
public class BannerController {

    private static final Logger logger = LoggerFactory.getLogger(BannerController.class);

    @Autowired
    private IBannerService bannerService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IConfigService configService;

    @RequestMapping("admin/banner/index")
    public String index(Model model) {
        Wrapper<Config> wrapper = new EntityWrapper<Config>()
                .eq("level", 1).eq("state", 1);
        MerchantApp mapp = redisService.getMApp(ObjectUtil.getMpid());

        if (mapp != null && mapp.getVersion() == 4) {
            wrapper.eq("type", CategoryEnum.hangyefenlei.getVal()).eq("mid", ObjectUtil.getMid());
            List<Config> business = configService.selectList(wrapper);
            model.addAttribute("business", business);
        }


        return "admin/banner";
    }

    @RequestMapping("/admin/banner/list")
    @ResponseBody
    public Page<Banner> list(@RequestParam(value = "limit", required = false) int limit,
                             @RequestParam(value = "offset", required = false) int offset) {
        User user = ObjectUtil.getSessionUser();

        Wrapper<Banner> wrapper = new EntityWrapper<Banner>().eq("mid", user.getMid());
        if (ObjectUtil.getMpid() != null) {
            wrapper.eq("mpid", user.getMpid());
        }
        wrapper.orderBy("sort", true);
        Page<Banner> page = bannerService.selectPage(new Page<Banner>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/banner/add")
    public String add(@Valid Banner bean,
                      BindingResult bindingResult) {

        logger.debug(">>>add start");
        logger.debug(JSON.toJSONString(bean));
//        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            logger.debug(JSON.toJSONString(bean));
        }

        if (bean.getState() == null) bean.setState(0);
        bean.setUid(ObjectUtil.getUid());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setCreatetime(new Date());
        bean.insert();

        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Banner@"+bean.getId()+"@insert", ActorRef.noSender());
        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_BANNER_MODIFY + "@" + bean.getId(), ActorRef.noSender());

        String rkey = Constants.REDIS_APP_INIT + bean.getMpid();
        redisService.del(rkey);

        logger.debug(">>>add over");
        return "admin/banner";
    }

    @RequestMapping("/admin/banner/getBannerById")
    @ResponseBody
    public Banner getBannerById(long id) {
        Banner banner = bannerService.selectById(id);
        return banner;
    }

    @RequestMapping("/admin/banner/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = bannerService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/banner/changeState")
    @ResponseBody
    public String changeState(long id, int state) {

        Banner bean = new Banner();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        bannerService.updateById(bean);
        String rkey = Constants.REDIS_APP_INIT + ObjectUtil.getMpid();
        redisService.del(rkey);
        return "success";
    }

    @RequestMapping("/admin/banner/modify")
    public String update(Banner bean) {
        logger.debug(">>>banner/modify info=" + JSON.toJSONString(bean));
        bean.setUid(ObjectUtil.getUid());
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = bannerService.updateById(bean);

        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Banner@"+bean.getId()+"@update", ActorRef.noSender());

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_BANNER_MODIFY + "@" + bean.getId(), ActorRef.noSender());

        String rkey = Constants.REDIS_APP_INIT + ObjectUtil.getMpid();
        redisService.del(rkey);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/admin/rm/file")
    @ResponseBody
    public JsonDO rmfile(@RequestParam(value = "ptype", required = false) String ptype,
                         @RequestParam(value = "feild", required = false) String feild,
                         @RequestParam(value = "id", required = false) String id
    ) {
        JsonDO json = new JsonDO();

        return json;
    }

    @RequestMapping(value = "/admin/upload/file", method = RequestMethod.POST)
    @ResponseBody
    public JsonDO uploadLogo(@RequestParam(value = "mfile", required = true) MultipartFile mfile,
                             @RequestParam(value = "f", required = false) String f,
                             @RequestParam(value = "type", required = true) String type) {
        JsonDO json = new JsonDO();
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();
        Long sid = ObjectUtil.getSid();

        if (mfile != null) {

            String fileName = mfile.getOriginalFilename();
            logger.debug(">>>mediafile=" + fileName);

            String rfilename = fileName.substring(0, fileName.lastIndexOf("."));
            if (rfilename.length() > 16) rfilename = rfilename.substring(0, 16);
            String extname = fileName.substring(fileName.lastIndexOf(".") + 1);
            String[] ts = type.split("_");
            String tyth = ts.length == 2 ? ts[0] + "/" + ts[1] + "/" : ts[0] + "/";

            String mcode = null;
            String uppath = null;
            Boolean iscdn = false;
            Merchant mch = redisService.getMerchant(ObjectUtil.getMid());
            MerchantApp mapp = redisService.getMApp(ObjectUtil.getMpid());

            if (ObjectUtil.getMpid() != null && mapp != null) {
                mcode = mapp == null ? "ungroup" : mapp.getMcode() + "/" + mapp.getMpcode();
                uppath = mapp.getIscdn() == 1 ? Constants.IMG_UPLOAD_PATH + "0cdn/" : Constants.IMG_UPLOAD_PATH;
                iscdn = mapp.getIscdn() == 1;
            } else if (ObjectUtil.getMid() != null && mch != null) {
                mcode = mch == null ? "ungroup" : mch.getMcode();
                uppath = mch.getIscdn() == 1 ? Constants.IMG_UPLOAD_PATH + "0cdn/" : Constants.IMG_UPLOAD_PATH;
                iscdn = mch.getIscdn() == 1;
            } else {
                mcode = "ungroup";
                uppath = Constants.IMG_UPLOAD_PATH;
            }
            String dirpath = uppath + mcode + "/" + tyth;

            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Date date = new Date();
//            String filename = EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname;
            String newfname = "";
            try {
                newfname = StringUtil.isContainChinese(rfilename) ? PinyinHelper.convertToPinyinString(rfilename, "", PinyinFormat.WITHOUT_TONE) : rfilename;
                newfname = newfname.replaceAll(" ", "").replaceAll("、", "").replaceAll("-", "");
                logger.debug(">>>after convertToPinyinString newfname=" + newfname);
            } catch (Exception e) {
                logger.error(">>>tpinyin error", e);
            }

            newfname = Strings.isNullOrEmpty(newfname) ? EncryptUtil.md5(date.getTime() + fileName).substring(0, 16) : newfname;
            if (newfname.length() > 16) newfname = newfname.substring(0, 16);

//            File file = new File(dirpath + EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname);// 保持原有文件格式
            File file = new File(dirpath + newfname + "." + extname);// 保持原有文件格式
            if (file.exists()) {
                newfname = EncryptUtil.md5(date.getTime() + fileName).substring(0, 16);
                file = new File(dirpath + newfname + "." + extname);
            }
            logger.debug(">>>targetFile getAbsolutePath=" + file.getAbsolutePath());
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            //保存
            try {
                file.createNewFile();
                logger.debug(">>>start to FileOutputStream");

                outputStream = new FileOutputStream(file);
                inputStream = mfile.getInputStream();
                byte temp[] = new byte[1024];
                int size = -1;
                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                    logger.info("File load size=" + size);
                    outputStream.write(temp, 0, size);
                }

                logger.info("File load success.");
            } catch (IOException e) {
                logger.warn("File load fail.", e);
            } finally {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("IO close error", e);
                }
            }

            String host = iscdn ? Constants.IMG_UPLOAD_HOST.replace("//img.", "//imgcdn.") : Constants.IMG_UPLOAD_HOST;
            String imgurl = file.getAbsolutePath().replace(uppath, host);
            json.setData(imgurl);

            if (!Strings.isNullOrEmpty(type) && !type.equals("resource")) {
                //type+pic+mid+mpid+ sid + mediatype+ tbtype+ fieldname
                if (Strings.isNullOrEmpty(f)) f = "pic";
                AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                        .tell("uploadfile" + "@" + imgurl + "@" + mid + "@" + mpid + "@" + sid
                                + "@" + Mediatype.picture.getVal() + "@" + type + "@" + f, ActorRef.noSender());
            }
        }

        json.setMsg("ok");
        return json;
    }

    @RequestMapping(value = "/admin/upload/vfile", method = RequestMethod.POST)
    @ResponseBody
    public Jinfo uploadVFile(@RequestParam(value = "mfile", required = true) MultipartFile mfile,
                             @RequestParam(value = "type", required = true) String type
    ) {
        Jinfo json = new Jinfo();
        if (mfile != null) {

            String fileName = mfile.getOriginalFilename();
            logger.debug(">>>mediafile=" + fileName);

            MerchantApp mapp = redisService.getMApp();
            String rfilename = fileName.substring(0, fileName.lastIndexOf("."));
            if (rfilename.length() > 16) rfilename = rfilename.substring(0, 16);
            String extname = fileName.substring(fileName.lastIndexOf(".") + 1);
            String[] ts = type.split("_");
            String tyth = ts.length == 2 ? ts[0] + "/" + ts[1] + "/" : ts[0] + "/";
            String mcode = mapp == null ? "ungroup" : mapp.getMcode() + "/" + mapp.getMpcode();
            String uppath = mapp.getIscdn() == 1 ? Constants.IMG_UPLOAD_PATH + "0cdn/" : Constants.IMG_UPLOAD_PATH;
            String dirpath = uppath + mcode + "/v/" + tyth;
            logger.info("======/api/upload/file dirpath=" + dirpath);

            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Date date = new Date();
            String newfname = "";
            try {
                newfname = StringUtil.isContainChinese(rfilename) ? PinyinHelper.convertToPinyinString(rfilename, "", PinyinFormat.WITHOUT_TONE) : rfilename;
                newfname = newfname.replaceAll(" ", "").replaceAll("、", "").replaceAll("-", "");
                logger.debug(">>>after convertToPinyinString newfname=" + newfname);
            } catch (Exception e) {
                logger.error(">>>tpinyin error", e);
            }

            newfname = Strings.isNullOrEmpty(newfname) ? EncryptUtil.md5(date.getTime() + fileName).substring(0, 16) : newfname;
            if (newfname.length() > 16) newfname = newfname.substring(0, 16);
            String path = dirpath + newfname + "." + extname;
            File file = new File(path);//保持原有文件格式

            if (file.exists()) {
                newfname = EncryptUtil.md5(date.getTime() + fileName).substring(0, 16);
                file = new File(dirpath + newfname + "." + extname);
            }
            logger.debug(">>>targetFile getAbsolutePath=" + file.getAbsolutePath());
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            int cout = 0;
            long allsize = 0;

            //保存
            try {
                file.createNewFile();
                logger.debug("------------------------------start to FileOutputStream");
                outputStream = new FileOutputStream(file);
                inputStream = mfile.getInputStream();
                byte temp[] = new byte[1024];
                int size = -1;

                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                    logger.info("File load size=" + size);
                    outputStream.write(temp, 0, size);
                    allsize += size;
                    cout++;
                }

                logger.info("File load success.");
            } catch (IOException e) {
                logger.warn("File load fail.", e);
            } finally {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("IO close error", e);
                }
            }
            //如果大于10M，则删除
            if (mapp.getMid() != 1 && mapp.getMid() != 20 && allsize > 1024 * 1024 * 10) {
                File dfile = new File(path);
                dfile.delete();

                json.setCode(1);
                json.setMsg("上传视频文件不能大于10M");
                return json;
            }
            logger.info("-----------------------------------uploadfile size cout=" + cout);

            String host = mapp.getIscdn().intValue() == 1 ?
                    Constants.IMG_UPLOAD_HOST.replace("//img.", "//imgcdn.") :
                    Constants.IMG_UPLOAD_HOST;

            String vurl = host + mcode + "/v/" + tyth + file.getName();

            Resource resource = new Resource();
            resource.setMid(ObjectUtil.getMid());
            resource.setMpid(ObjectUtil.getMpid());
            resource.setSid(ObjectUtil.getSid());
            resource.setUid(ObjectUtil.getUid());

            resource.setName(file.getName());
            resource.setPic(vurl);
            resource.setSize(allsize);
            resource.setRtype(Rtype.vedio.getVal());
            resource.setCreatetime(new Date());

            //读取缩略图+时长
            try {
                String thumburl = host + mcode + "/v/" + tyth + file.getName().replace("." + extname, ".jpg");
                resource.setThumb(thumburl);
                Long duration = VideoUtil.getDuration(path);
                resource.setDuration(duration);
                if (mapp.getMid() != 1 && mapp.getMid() != 20 && resource.getDuration() > 45) {

                    File dfile2 = new File(path);
                    dfile2.delete();

                    json.setCode(1);
                    json.setMsg("上传视频文件时长不能超过45秒");
                    return json;
                }

                JSONObject jo = VideoUtil.fetchPic(path, path.replace("." + extname, ".jpg"));
                resource.setMheight(jo.getInteger("mheight"));
                resource.setPixel(jo.getInteger("owidth") + "x" + jo.getInteger("oheight"));
            } catch (Exception e) {
                logger.error("----------------VideoUtil process error", e);
            }

            resource.insert();
            json.setData(vurl);
            json.setExtra(resource);
        }

        json.setMsg("ok");
        return json;
    }

}
